package com.aube.multiscreen;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aube.R;
import com.aube.control.player.AbstractVideoHelper;
import com.aube.control.player.MajorTextureVideoHelper;
import com.aube.control.player.MultiVideoBalanceAdapter;
import com.aube.control.player.TextureVideoHelper;
import com.aube.model.VideoItem;
import com.aube.model.VrItem;
import com.aube.views.RingLoading;
import com.aube.views.vote.AnimatorHelper;
import com.huyn.baseframework.model.ChannelDetail;
import com.huyn.baseframework.model.VideoPlayModel;
import com.huyn.baseframework.utils.Constant;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.UmengUtils;
import com.huyn.baseframework.utils.Utils;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 15/11/14.
 * 从熟悉的味道开始,对关闭声音开关以及边框的处理
 * 6/12
 */
public class CameraCardView extends FrameLayout {

    protected final String TAG = getClass().getSimpleName();

    protected Context context;
    protected TextView mTitle;
    protected View mTool;
    protected View mRoot;
    protected RingLoading mLoading;
    protected ImageView mZoom;
    protected ImageView mClose;
    protected TextView mDes;

    private TextureView mSurface;

    /************从熟悉的味道开始,对关闭声音开关以及边框的处理*************/
    protected ImageView mVoice;
    protected View mAudioMask;
    /****************************************************************/

    protected AbstractVideoHelper mHelper;
    protected long lastPosition = 0;
    protected VideoItem mVideoItem;
    protected Paint mPaint;
    protected AtomicBoolean mVideoPrepared = new AtomicBoolean(false);
    protected boolean isNormalSize = true;
    protected static final int PADDING = 5;
    protected IVideoController iController;

    private boolean showClickGuide = false;
    private IVideoParentConnector iVideoParentConnector;

    protected VideoPlayModel mVideo;

    public CameraCardView(Context context) {
        this(context, null);
    }
    public CameraCardView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public CameraCardView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        mPaint = new Paint();
        mPaint.setAntiAlias(true);

        inflateView();
    }

    protected void inflateView() {
        LayoutInflater.from(context).inflate(R.layout.layout_camera_card, this);
        mRoot = findViewById(R.id.card_layout);
        mSurface = (TextureView) findViewById(R.id.card_video);
        mTool = findViewById(R.id.card_tools);

        mZoom = (ImageView) findViewById(R.id.card_zoom);
        mClose = (ImageView) findViewById(R.id.card_close);

        mTitle = (TextView) findViewById(R.id.card_title);
        mDes = (TextView) findViewById(R.id.card_des);

        mVoice = (ImageView) findViewById(R.id.card_voice_toggle);
        mVoice.setTag(R.id.video_voice, false);
        mAudioMask = findViewById(R.id.card_audio_mask);

        mLoading = (RingLoading) findViewById(R.id.card_loading);
    }

    public void showLoading() {
        if(mLoading.getVisibility() != View.VISIBLE)
            mLoading.setVisibility(View.VISIBLE);
    }

    public void hideLoading() {
        if(mLoading.getVisibility() == View.VISIBLE)
            mLoading.setVisibility(View.GONE);
    }

    public void initSideCardState() {
        mTool.setVisibility(View.GONE);
        mDes.setVisibility(View.VISIBLE);
    }

    public TextureView getTextureView() {
        return mSurface;
    }

    public void setIVideoController(IVideoController controller) {
        this.iController = controller;
    }

    public void initEvent() {
        mZoom.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                switchViewSize();
            }
        });
    }

    public void switchViewSize() {
        if(iController != null)
            iController.exchangeViewSize(mTitle.getText().toString(), isNormalSize, isVr() && supportVRMotionMode());

        //changeicon
        switchWindowSize(isNormalSize);
    }

    /**
     * TODO oopo r7和红米手机的vrmotion模式有点bug
     * @return
     */
    public boolean supportVRMotionMode() {
        if(StringUtils.isNotBlank(Constant.APP_MOBILETYPE)) {
            String type = Constant.APP_MOBILETYPE.toLowerCase();
            if(type.contains("redmi") || type.contains("oppo"))
                return false;
            return true;
        }
        return false;
    }

    public boolean isVr() {
        return false;
    }

    public void updateTitle(String title) {
        mTitle.setText(title);
        mDes.setText(title);
    }

    public void hideTitle(boolean showTopTool) {
        mDes.setVisibility(View.VISIBLE);
        mTool.setVisibility(View.VISIBLE);

        mTitle.setVisibility(View.GONE);
        mZoom.setVisibility(View.GONE);
        if(showTopTool) {
            mClose.setVisibility(View.VISIBLE);
        } else {
            mClose.setVisibility(View.GONE);
        }
    }

    public void showTitle() {
//        mTool.setVisibility(View.VISIBLE);
        AnimatorHelper.alphaAnim(mTool, 0f, 1f);

        mClose.setVisibility(View.GONE);
        mZoom.setVisibility(View.VISIBLE);
        mTitle.setVisibility(View.VISIBLE);

        mDes.setVisibility(View.GONE);
    }

    public void hideAll() {
        mTool.setVisibility(View.GONE);

        mClose.setVisibility(View.GONE);
        mZoom.setVisibility(View.GONE);
        mTitle.setVisibility(View.GONE);

        mDes.setVisibility(View.GONE);
    }

    public void clear() {
        mTool.setVisibility(View.GONE);
        mDes.setVisibility(View.GONE);
    }

    public void initClick(final int i, boolean enableSound) {
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.Log(TAG, "perform onclick on root");
                if (iController != null) {
                    int currentIndex = iController.getCurrentIndex();
                    if (currentIndex == i) {
                        Utils.Log(TAG, "show tools");
                        iController.showTools();
                    } else {
                        Utils.Log(TAG, "switch to big video with current main video");
                        iController.switchView(v);
                        ChannelDetail channelDetail = iController.getChannelDetail();
                        if(iController.isMiddleMode()) {
                            UmengUtils.reportUmengEvent(context, UmengUtils.EVENT_SWITCH_VIDEO_IN_MIDDLE_SCREEN, UmengUtils.appendLabels(channelDetail.videoid, channelDetail.videoTitle, getTitle()));
                        } else {
                            UmengUtils.reportUmengEvent(context, UmengUtils.EVENT_SWITCH_VIDEO_IN_FULL_SCREEN, UmengUtils.appendLabels(channelDetail.videoid, channelDetail.videoTitle, getTitle()));
                        }
                    }
                }
            }
        });

        mClose.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.Log(TAG, "remove from pip to side");
                if (iController != null)
                    iController.removeFromMainPic(CameraCardView.this, (String) getTag());
            }
        });

        mVoice.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean on = (boolean) mVoice.getTag(R.id.video_voice);
                mHelper.manageSound(!on);

                Utils.Log("VOICE", "...................performClick");
                managePadding(true, true);

                //主镜头的声音切换不影响分镜头的 deprecated on Jan 12th 2017
                //int id = Integer.parseInt((String) getTag());
                //if (iController != null && id > 0)
                //    iController.exchangeSound(id);
            }
        });

        if(enableSoundSwitch() && i > 0) {
            if (enableSound && i > 0) {
                mVoice.setVisibility(View.VISIBLE);
                mAudioMask.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        Rect mTmpRect = new Rect();
        child.getHitRect(mTmpRect);

        drawBorder(canvas, mTmpRect);
        boolean ret = super.drawChild(canvas, child, drawingTime);
        return ret;
    }

    private void drawBorder(Canvas canvas, Rect rect) {
        if(!isCurrentView() && ((enableSoundSwitch() && isSoundOn()) || isInPIPMode())) {
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setColor(0xff5f5f5f);
            mPaint.setStrokeWidth(1);
            canvas.drawRect(rect.left, rect.top, rect.right, rect.bottom, mPaint);

            mPaint.setColor(0x80ffffff);
            mPaint.setStyle(Paint.Style.FILL);
            canvas.drawRect(rect.left +1, rect.top +1, rect.right -1, rect.bottom -1, mPaint);
        } else if(iController != null && iController.isMiddleMode()) {
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setColor(0xff5f5f5f);
            mPaint.setStrokeWidth(1);
            int padding = PADDING - 1;
            canvas.drawRect(rect.left +padding, rect.top +padding, rect.right -padding, rect.bottom -padding, mPaint);
        }
    }

    /**
     * 是否是主镜头
     * @return
     */
    public boolean isCurrentView() {
        int id = Integer.parseInt((String) getTag());
        if(iController != null)
            return iController.getCurrentIndex() == id;
        return false;
    }

    /**
     * 重置主镜头的声音相关东西
     */
    public void resetSoundState() {
        if(mHelper != null)
            mHelper.manageSound(true);
        showBorder(false);
        mVoice.setVisibility(View.GONE);
        mAudioMask.setVisibility(View.GONE);
        Utils.Log("VOICE", "...................resetSoundState");
    }

    public void managePadding(boolean showBorder, boolean showVoice) {
        Utils.Log(TAG, "managePadding:" + getVideoId() + "_____showBorder:" + showBorder + "/showVoice:" + showVoice + "/enableSoundSwitch:" + enableSoundSwitch() + "/mVideoPrepared:" + mVideoPrepared.get());
        if(enableSoundSwitch() && mVideoPrepared.get()) {
            boolean soundOn = mHelper.isSoundOn();

            if(showVoice) {
                mVoice.setVisibility(View.VISIBLE);
                mAudioMask.setVisibility(View.VISIBLE);

                mVoice.setImageResource(soundOn ? R.drawable.icon_video_voiceon : R.drawable.icon_video_voiceoff);
                mVoice.setTag(R.id.video_voice, soundOn);
            } else {
                mVoice.setVisibility(View.GONE);
                mAudioMask.setVisibility(View.GONE);
            }
        } else {
            mVoice.setVisibility(View.GONE);
            mAudioMask.setVisibility(View.GONE);
        }
        showBorder(showBorder);

        invalidate();
    }

    private boolean isInPIPMode() {
        if(iVideoParentConnector != null)
            return iVideoParentConnector.isInPIPMode((String) getTag());
        return false;
    }

    /**
     * 展示喇叭和mask
     * @param inCenter
     */
    public void manageAudioAndMask(boolean inCenter) {
        changeAudioTogglePosition(inCenter);
        invalidate();
    }

    @TargetApi(17)
    public void changeAudioTogglePosition(boolean inCenter) {
        if(!enableSoundSwitch() || !mVideoPrepared.get())
            return;
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mVoice.getLayoutParams();
        if(Build.VERSION.SDK_INT >= 17) {
            if (inCenter) {
                params.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                params.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT);

                params.addRule(RelativeLayout.CENTER_IN_PARENT);
                mAudioMask.setVisibility(View.VISIBLE);
            } else {
                params.removeRule(RelativeLayout.CENTER_IN_PARENT);

                params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                mAudioMask.setVisibility(View.GONE);
            }
        } else {
            if (inCenter) {
                params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 0);
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0);

                params.addRule(RelativeLayout.CENTER_IN_PARENT);
                mAudioMask.setVisibility(View.VISIBLE);
            } else {
                params.addRule(RelativeLayout.CENTER_IN_PARENT, 0);

                params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                mAudioMask.setVisibility(View.GONE);
            }
        }

        int padding = getResources().getDimensionPixelOffset(inCenter ? R.dimen.autio_margin_center :R.dimen.autio_margin_corner);
        mVoice.setLayoutParams(params);
        mVoice.setPadding(padding, padding, padding, padding);
    }

    public void showBorder(boolean yes) {
        if(yes)
            mRoot.setPadding(PADDING, PADDING, PADDING, PADDING);
        else
            mRoot.setPadding(0, 0, 0, 0);
    }

    public void soundOff() {
        mHelper.manageSound(false);
        managePadding(true, true);
        Utils.Log("VOICE", "...................soundOff");
    }

    public void openSound() {
        mHelper.manageSound(enableSoundSwitch());
    }

    /**
     * 声音开关
     * @param soundOn
     */
    public void manageSound(boolean soundOn) {
        mHelper.manageSound(soundOn);
    }

    public void switchWindowSize(boolean toFull) {
        Utils.Log("VOICE", "...................switchWindowSize");
        if(toFull) {
            AnimatorHelper.alphaAnim(mTool, 1, 0);

            managePadding(false, false);

            ChannelDetail channelDetail = iController.getChannelDetail();
            UmengUtils.reportUmengEvent(context, UmengUtils.TO_FULL_SCREEN, UmengUtils.appendLabels(channelDetail.videoid, channelDetail.videoTitle, getTitle()));
        } else {
            showTitle();

            managePadding(true, false);
        }

        isNormalSize = !toFull;
    }

    public void manageStateInPIP(boolean showDes) {
        Utils.Log(TAG, "manageStateInPIP on " + getVideoId() + " showDes :" + showDes);
        mTool.setVisibility(View.VISIBLE);
        mClose.setVisibility(View.VISIBLE);
        mTitle.setVisibility(View.GONE);
        mZoom.setVisibility(View.GONE);

        if (showDes) {
            mDes.setVisibility(View.VISIBLE);
        } else {
            mDes.setVisibility(View.GONE);
        }

        manageAudioAndMask(!showDes);
    }

    public String getTitle() {
        if(mTitle == null)
            return "";
        return mTitle.getText().toString();
    }

    public void onVideoPrepared() {
        mVideoPrepared.set(true);
    }

    public AbstractVideoHelper play(final int i, VideoItem item, final long startTime, boolean play, final IVideoController controller) {
        this.mVideo = item.getVideo();
        mHelper = new TextureVideoHelper(mSurface, context, mVideo, item.enableSound());
        mHelper.setStartTime(startTime);
        mHelper.initPlayState(play);
        mHelper.setPlayCallback(new AbsPlayCallback() {
            @Override
            public void endPlay() {
                hideLoading();
            }

            @Override
            public void updatePlay(long current, long duration) {
                if (lastPosition != current && mHelper.isPlaying()) {
                    hideLoading();
                    lastPosition = current;
                } else {
                    showLoading();
                }

                if(MultiVideoBalanceAdapter.getInstance().isLowExperience() && controller != null) {
                    controller.updateProgressBySubVideo(current + mHelper.getStartTime());
                }

                if(current > 500) {
                    //显示声音图标
                    if(mVideoPrepared.get())
                        return;
                    //show voice and mask
                    mVideoPrepared.set(true);

                    //show voice icon if needed
                    boolean isCurrentVideo = isCurrentView();
                    Utils.Log("VOICE", "...................updatePlay");
                    managePadding(!isCurrentVideo, !isCurrentVideo);

                    changeAudioTogglePosition(!isInPIPMode());
                }
            }

//            @Override
//            public void clearLoading() {
//                hideLoading();
//            }

            @Override
            public void syncSuccess() {
                //可以显示引导了
                if(showClickGuide && iVideoParentConnector != null) {
                    showClickGuide = false;
                    iVideoParentConnector.showClickGuide(CameraCardView.this);
                }
            }
        });

        showLoading();
        initContent(item, i, controller);
        return mHelper;
    }

    public String getVideoId() {
        if(mVideo != null)
            return mVideo.videoId;
        if(mVideoItem != null)
            return mVideoItem.getVideoId();
        return "";
    }

    public void setHelper(AbstractVideoHelper helper) {
        this.mHelper = helper;
    }

    public void initContent(VideoItem item, int i, IVideoController controller) {
        this.mVideoItem = item;
        mTitle.setText(item.videoTitle);
        mDes.setText(item.videoTitle);

        initClick(i, item.enableSound());
        setIVideoController(controller);
        initEvent();

        //主镜头不显示border
        showBorder(i != 0);
    }

    public boolean enableSoundSwitch() {
        boolean enable = false;
        if(iController != null)
            enable = iController.enableSoundSwitch();
        if(enable) {
            int id = Integer.parseInt((String) getTag());
            if(id == 0)
                return true;
            else
                return mVideoItem.enableSound();
        } else {
            return false;
        }
    }

    public boolean isSoundOn() {
        if(mHelper != null)
            return mHelper.isSoundOn();
        return false;
    }

    public void enableClickGuide() {
        showClickGuide = true;
    }

    public void setIVideoParentConnector(IVideoParentConnector listener) {
        this.iVideoParentConnector = listener;
    }

    public AbstractVideoHelper getVideoHelper(VideoPlayModel video, String x, String y, AbsPlayCallback playCallback) {
        this.mVideo = video;
        mHelper = new MajorTextureVideoHelper(getTextureView(), context, video, playCallback);
        return mHelper;
    }

    public void onDestroy() {
        if(mHelper != null) {
            mHelper.onDestroy();
            mHelper = null;
        }
    }

    public void onResume() {

    }

    public void onPause() {

    }

    public void attachVrVideo(VrItem vr, long startTime) {

    }

    public void replaceVrVideo(VrItem vr, long startTime) {

    }

    public void detachVrVideo() {

    }

    public void suspendPlayer() {
        if(mHelper != null)
            mHelper.pausePlay();
        hideLoading();
    }

    public void notifyPlayer(long current) {
        if(mHelper != null)
            mHelper.startPlay(current);
    }

    public boolean startPlayer() {
        if(mHelper != null)
            return mHelper.startPlay();
        return false;
    }

    public void stopPlayer() {
//        mHelper.stopPlayer();
    }

    public void removeMask(){}

    public boolean consumeTouchEvent() {
        return false;
    }

    public void seekTo(int progress) {
        mHelper.seekTo(progress);
    }

    public void reloadVideoIfNeed() {
        if(mHelper != null)
            mHelper.reloadVideoIfNeed();
    }

}
